/*
 * user_tick_timer.c
 *
 *  Created on: Jan 9, 2025
 *      Author: Lenovo
 */
#include "debug.h"
#include "user_includes.h"

volatile unsigned int g_u16timer_delay[MAX_TIMER_DELAY];                         /*֨ʱǷғʱ*/
static uint32_t tick_cnt = 0;
static uint8_t time_init_flag = 0;
/*********************************************************************
 * @fn      TIM1_UP_IRQHandler
 *
 * @brief   This function handles TIM1 UP exception.
 *
 *
 * @return  none
 */
void TIM3_IRQHandler(void) __attribute__((interrupt("WCH-Interrupt-fast")));
void TIM3_IRQHandler(void)
{


    if(TIM_GetITStatus(TIM3, TIM_IT_Update)==SET)
    {
        tick_cnt++;
        if(tick_cnt % 1000 == 0){
            printf("%d\r\n", tick_cnt);
           // PowerOfftimes_reduce();
        }
        for (uint8_t i=0; i<MAX_TIMER_DELAY; i++) {
            if (g_u16timer_delay[i] > 0) {
                g_u16timer_delay[i]--;
            }
        }
        beep_manage();
        TIM_ClearITPendingBit( TIM3, TIM_IT_Update );
    }

}

static void TIM3_INT_Init( u16 arr, u16 psc)
{
    if(time_init_flag){
        return;
    }

    NVIC_InitTypeDef NVIC_InitStructure={0};
    TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure={0};

    RCC_PB1PeriphClockCmd(RCC_PB1Periph_TIM3, ENABLE );

    TIM_TimeBaseInitStructure.TIM_Period = arr;
    TIM_TimeBaseInitStructure.TIM_Prescaler = psc;
    TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
   // TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 10;//当次数达到重复计数值寄存器（RPTCR）里设置的次数时，可以产生特定事件。
    TIM_TimeBaseInit( TIM3, &TIM_TimeBaseInitStructure);

    TIM_ClearITPendingBit( TIM3, TIM_IT_Update );

    NVIC_InitStructure.NVIC_IRQChannel =TIM3_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority =0;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority =3;
    NVIC_InitStructure.NVIC_IRQChannelCmd =ENABLE;
    NVIC_Init(&NVIC_InitStructure);

    TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE);

    TIM_Cmd(TIM3, ENABLE);                                          //TIM3使能
    time_init_flag = 1;

}

void user_tick_timer_init(void){
    TIM3_INT_Init(1000-1, 96-1);
}

void user_tick_timer_disable(void){
    if(!time_init_flag){
        return;
    }
    TIM_Cmd(TIM3,DISABLE);
    time_init_flag = 0;
}

void user_tick_timer_restart(void){
    if(time_init_flag){
        return;
    }
    tick_cnt = 0;
    TIM3->CNT = 0;
    TIM_Cmd(TIM3, ENABLE);
    time_init_flag = 1;
}


